package com.ruiyian.netty.nettyUdpserver;

import com.ruiyian.common.constant.ActiveModule;
import com.ruiyian.common.constant.FinsStatus;
import com.ruiyian.common.core.redis.RedisCache;
import com.ruiyian.common.utils.JSON;
import com.ruiyian.common.utils.spring.SpringUtils;
import com.ruiyian.netty.nettyserver.MyChannelHandlerPool;
import com.ruiyian.system.domain.IceDetect;
import com.ruiyian.system.mapper.IceDetectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 报文处理器
 */
@Component
@ChannelHandler.Sharable
public class NettyUdpHandler extends SimpleChannelInboundHandler<DatagramPacket> {


    private static final Logger LOG = LoggerFactory.getLogger(NettyUdpHandler.class);

    private static AtomicInteger atomicInteger=new AtomicInteger(0);

    private Map<String, String> bridgeDataMap = new HashMap<String, String>();

    // redis缓存依赖
    private static RedisCache redisCache;

    private static IceDetectMapper iceDetectMapper;

    static {
        redisCache = SpringUtils.getBean(RedisCache.class);
        iceDetectMapper = SpringUtils.getBean(IceDetectMapper.class);
    }



    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket dp) {
        try {
            int length = dp.content().readableBytes();
            //分配一个新的数组来保存具有该长度的字节数据
            byte[] array = new byte[length];
            //将字节复制到该数组
            dp.content().getBytes(dp.content().readerIndex(), array);
            //删除状态定义
            char del_flag = '0';
            // 新建字符串缓存
            StringBuilder hexStringBufferequipid = new StringBuilder();
            StringBuilder hexStringBufferwarn = new StringBuilder();
            StringBuilder hexStringBufferflag = new StringBuilder();
            // 循环处理数据
            for (int i=0;i<array.length;i++) {
                // 获取设备id
                if(i>=3&&i<=6){
                    String hexString = String.format("%c", array[i]);
                    hexStringBufferequipid.append(hexString);
                }
                //获取告警状态
                else if(i==12){
                    String hexString = String.format("%d", array[i]);
                    hexStringBufferwarn.append(hexString);
                }
                //结束位，在hexString中添加del_flag
                else if(i==19){
                    String hexString = String.format("%c", del_flag);
                    hexStringBufferflag.append(hexString);
                }

            }
            // 温度整形值
            int tempIntData = Byte.toUnsignedInt(array[8])*256 + Byte.toUnsignedInt(array[9]);
            String tempStrData = String.format("%d.%d", tempIntData/10, tempIntData%10);
            // 湿度整形值
            int humiIntData = Byte.toUnsignedInt(array[10]);
            String humiStrData = String.format("%d", humiIntData);
                // 时间
            Long timeStamp = System.currentTimeMillis();
            bridgeDataMap.put("timestamp", String.format("%d", timeStamp));
            // 温度
            bridgeDataMap.put("temp", tempStrData);
            // 湿度
            bridgeDataMap.put("humi", humiStrData);
            //告警
            bridgeDataMap.put("warning", hexStringBufferwarn.toString());
            //删除标志位
            bridgeDataMap.put("del_flag", hexStringBufferflag.toString());
            // 存到缓存
            redisCache.setCacheObject("bridge/icedetect/"+hexStringBufferequipid.toString(), bridgeDataMap);

            System.out.println(bridgeDataMap);
            // 查看激活的是哪一个模块
            String currentactivemodule = redisCache.getCacheObject("CurrentActiveModule");
            if(currentactivemodule!=null){
                if(currentactivemodule.equals(ActiveModule.ICE_DETECT_DC)||currentactivemodule.equals(ActiveModule.ICE_DETECT_TTL)){
                    JSONObject jsonReturn = new JSONObject();
                    Map<String,String> deviceInfo = new HashMap<String,String>();
                    jsonReturn.put("operateType", "query");
                    jsonReturn.put("code", FinsStatus.SUCCESS);
                    jsonReturn.put("msg", hexStringBufferequipid.toString()+"在线");
                    jsonReturn.put("deviceInfo", bridgeDataMap);
                    MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(JSON.stringify(jsonReturn)));
                }
            }
//            System.out.println(String.format("凝冰数据:%s 字节长度：%d", hexStringBufferequipid.toString(),length));
//            LOG.info("收到UDP报文，报文内容:{} 包处理个数:{}", new String(array),atomicInteger.incrementAndGet());
//            System.out.println("-------------------------------------------------");
//            System.out.println(bridgeDataMap);
//            System.out.println(String.format("%d", timeStamp));
//            System.out.println(hexStringBuffertemp.toString());
//            System.out.println(hexStringBufferhumi.toString());
//            System.out.println(hexStringBufferequipid.toString());
//            System.out.println(hexStringBufferflag.toString());
//            System.out.println(hexStringBufferwarn.toString());

            //icedetect赋值
            IceDetect icedetect = new IceDetect();
            icedetect.setHumidity(Float.parseFloat(humiStrData));
            icedetect.setDevice_id(String.valueOf(hexStringBufferequipid.toString()));
            icedetect.setTemperature(Float.parseFloat(tempStrData));
            icedetect.setTimestamp(String.valueOf(timeStamp));
            icedetect.setWarning(String.valueOf(hexStringBufferwarn.toString()));
            icedetect.setDel_flag(hexStringBufferflag.toString().charAt(0));

            //传感数据存入
            iceDetectMapper.save(icedetect);
            //查询并返回时间戳timeStamp最小值条目的id
            Long earliestDataId = iceDetectMapper.findEarliestDataId();
            //删除timeStamp最小值条目的id

            Long allDataNumber = iceDetectMapper.countByExample();
            if (allDataNumber>=60){
                iceDetectMapper.delete(earliestDataId);
            }

            System.out.println("allDataNumber-------------------------------------------------");
            System.out.println(allDataNumber);

        } catch (Exception e) {
            LOG.error("报文处理失败，失败原因:{}", e.getMessage(), e);
        }
    }
}
